//导入 axios
import axios from 'axios';
import moment from 'moment';
import swal from 'sweetalert';
//获取 token
let token = localStorage.getItem('token');
//判断
if (!token) {
  //用户没有登录, 跳转页面进行登录
  location.href = '/login.html';
}
//获取 accounts 元素 div
let accountsDiv = document.querySelector('.accounts');

//直接发送 AJAX 请求获取所有的账单
(async () => {
  //发送请求 获取所有的账单
  let result = await axios.get('http://127.0.0.1:3001/api/account', {
    headers: {
      token: token
    }
  });
  let str = '';
  //动态渲染结果值
  result.data.data.accounts.forEach(item => {
    //拼接字符串
    str += `<div class="panel panel-${item.type === 1 ? 'success' : 'danger'}">
              <div class="panel-heading">${moment(item.date).format('YYYY-MM-DD')}</div>
              <div class="panel-body">
                <div class="col-xs-5"><a href="/account-edit.html?id=${item._id}">${item.title}</a></div>
                <div class="col-xs-2 text-center">
                  <span class="label label-${item.type === 1 ? 'success' : 'danger'}">${item.type === 1 ? '收入' : '支出'}</span>
                </div>
                <div class="col-xs-3 text-right">${item.money} 元</div>
                <div class="col-xs-1 text-right">
                  <span
                    data-id="${item._id}"
                    class="glyphicon glyphicon-remove del"
                    aria-hidden="true"
                  ></span>
                </div>
              </div>
            </div>`
  })
  //设置文本的操作
  accountsDiv.innerHTML = str;
})();

(() => {
  //获取 accounts 元素
  accountsDiv.addEventListener('click', async function (e) {
    //判断事件源  add  remove contains 包含
    if (e.target.classList.contains('del')) {
      //获取元素身上的 id 属性值
      let id = e.target.dataset.id;
      //发送 AJAX 请求
      let result = await axios.delete(`http://127.0.0.1:3001/api/account/${id}`, {
        headers: {
          token: token
        }
      });
      if (result.data.code === '0000') {
        //删除成功之后, 跳转账单的列表页
        swal({
          title: "温馨提示",
          text: "删除成功",
          icon: "success",
          buttons: true,
          dangerMode: false,
        }).then(() => {
          //刷新
          // location.href = location.href;
          // location.reload(true);//强制刷新
          location.reload();
        })
      }else{
        swal({
          title: "温馨提示",
          text: "删除失败",
          icon: "error",
          dangerMode: true,
        })
      }
    }
  })
})();